package com.GLM.Viewer.Party;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

import com.GLM.Constants.Constant;
import com.GLM.Entity.MsgEntity;
import com.GLM.Entity.StoreEntivity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.ViewsUtil;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Map.MapMainActivity;
import com.GLM.Viewer.Users.UserInfoDetailActivity;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class PartyStoreDetailActivity extends Activity {
	private final static int PARTYDETAIL_LOADING = 111;
	private final static int PARTYDETAIL_LONDED = 222;
	private StoreEntivity mStore;
	Button storePhoneBtn;
	private ListView mCommentsList;
	private SimpleAdapter mCommentsAdapter;
	private List<Map<String, Object>> mCommentsItems = new ArrayList<Map<String, Object>>();
	private String[] commentItemKeys = new String[] { "comUser", "comTime", "comContent" };
	private int[] commentItemIds = new int[] { R.id.view_newparty_comitem_name, R.id.view_newparty_comitem_time, R.id.view_newparty_com_content };
	private Map<String, Integer> commentinfos = new HashMap<String, Integer>();
	private AsynImageLoader imageLoader = new AsynImageLoader();

	View mInputFieldMoreLines;
	EditText mInputFieldMoreLinesEditText;
	Animation mAnimIn;
	Animation mAnimOut;
	InputMethodManager imm;
	private String parentActivity;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Thread thread;
			switch (msg.what) {
			case PARTYDETAIL_LOADING:
				thread = new Thread(new Runnable() {
					public void run() {
						initCommentsInfos();
						mCommentsAdapter = new SimpleAdapter(PartyStoreDetailActivity.this, mCommentsItems, R.layout.view_newparty_location_comlistitem, commentItemKeys, commentItemIds);
						mHandler.sendEmptyMessage(PARTYDETAIL_LONDED);
					}

				});
				thread.start();
				break;

			case PARTYDETAIL_LONDED:
				if (mCommentsAdapter != null) {
					mCommentsList.setAdapter(mCommentsAdapter);

					bindItemClick();
					setListViewHeightBasedOnChildren(mCommentsList);
				}
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_newparty_location_itemdetail);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		Intent intent = getIntent();
		mStore = (StoreEntivity) intent.getExtras().getSerializable("store");
		parentActivity = intent.getStringExtra("ParentActivity");
		initViews();
		initInputFields();
		initAnimation();

		mCommentsList = (ListView) findViewById(R.id.newparty_location_comListView);
		initRegisterInputFieldButton();
		mHandler.sendEmptyMessage(PARTYDETAIL_LOADING);

	}

	private void initInputFields() {
		mInputFieldMoreLines = findViewById(R.id.inputfield_moreline);
		mInputFieldMoreLines.setVisibility(View.GONE);
		mInputFieldMoreLinesEditText = (EditText) findViewById(R.id.inputfieldmoreline_edittext);
	}

	private void initAnimation() {
		mAnimIn = AnimationUtils.loadAnimation(this, R.anim.anim_register_in);
		mAnimOut = AnimationUtils.loadAnimation(this, R.anim.anim_register_out);
	}

	private void initRegisterInputFieldButton() {
		// more line
		Button inputMoreLineCancelButton = (Button) findViewById(R.id.inputfieldmoreline_cancelbutton);
		inputMoreLineCancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				hideMoreLinesInputField();
			}
		});

		Button inputMoreLineOkButton = (Button) findViewById(R.id.inputfieldmoreline_okbutton);
		inputMoreLineOkButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String comContext = mInputFieldMoreLinesEditText.getText().toString().trim();
				if (!comContext.equals("")) {
					hideMoreLinesInputField();
					initComment(comContext);
					mCommentsItems.clear();
					initCommentsInfos();

					mCommentsAdapter = new SimpleAdapter(PartyStoreDetailActivity.this, mCommentsItems, R.layout.view_newparty_location_comlistitem, commentItemKeys, commentItemIds);
					mCommentsList.setAdapter(mCommentsAdapter);
				}
			}
		});

	}

	private void showMoreLinesInputField() {
		mInputFieldMoreLines.startAnimation(mAnimIn);
		mInputFieldMoreLines.setVisibility(View.VISIBLE);
		mInputFieldMoreLinesEditText.requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	private void hideMoreLinesInputField() {
		mInputFieldMoreLinesEditText.setText("");
		mInputFieldMoreLinesEditText.clearFocus();
		mInputFieldMoreLines.startAnimation(mAnimOut);
		mInputFieldMoreLines.setVisibility(View.GONE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	public void initViews() {
		TextView storeName = (TextView) findViewById(R.id.newparty_location_locname);
		TextView storeAddr = (TextView) findViewById(R.id.newparty_location_locaddress);
		ImageView storeImage = (ImageView) findViewById(R.id.newparty_location_storeview);
		TextView storeIntroduce = (TextView) findViewById(R.id.newparty_location_introduce);
		storePhoneBtn = (Button) findViewById(R.id.newparty_location_locphone);

		storeName.setText(mStore.getMg_name());
		storeAddr.setText(mStore.getMg_address());
		storeIntroduce.setText(mStore.getMg_introduce());
		if (mStore.getMg_phone() != null)
			storePhoneBtn.setText(mStore.getMg_phone());

		storePhoneBtn.setOnClickListener(clickListeners);
		String imageUrl = mStore.getMg_picture();

		if (imageUrl != null && imageUrl != "") {
			storeImage.setVisibility(View.VISIBLE);
			imageLoader.showImageAsyn(storeImage, Constant.URL_MSGGROUP_BIG + imageUrl, R.drawable.glm_white);
		} else {
			storeImage.setVisibility(View.GONE);
		}

		Button BuildpartyBtn = (Button) findViewById(R.id.newparty_location_buildparty);
		BuildpartyBtn.setOnClickListener(clickListeners);
		Button commentBtn = (Button) findViewById(R.id.newparty_location_comment);
		commentBtn.setOnClickListener(clickListeners);
		Button likeplusBtn = (Button) findViewById(R.id.newparty_location_likebtn);
		likeplusBtn.setOnClickListener(clickListeners);
		Button locateBtn = (Button) findViewById(R.id.newparty_location_locate_button);
		locateBtn.setOnClickListener(clickListeners);
	}

	public void bindItemClick() {
		mCommentsList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
				// TODO Auto-generated method stub
				TextView nameTextView = (TextView) view.findViewById(R.id.view_newparty_comitem_name);
				TextView dateTextView = (TextView) view.findViewById(R.id.view_newparty_comitem_time);
				String key = nameTextView.getText().toString() + "-" + dateTextView.getText().toString();
				int user_id = commentinfos.get(key);
				Intent intent = new Intent(PartyStoreDetailActivity.this, UserInfoDetailActivity.class);
				intent.putExtra(Constant.INTENT_USER_ID, user_id);
				startActivity(intent);
			}
		});

		mCommentsList.setOnScrollListener(scrollListener);
	}

	OnScrollListener scrollListener = new OnScrollListener() {

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub

		}

		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			loadCommentListItem();

		}
	};

	public void loadCommentListItem() {
		int count = mCommentsList.getChildCount();
		for (int i = 0; i < count; i++) {
			View view = mCommentsList.getChildAt(i);
			if (i % 2 == 0) {
				view.setBackgroundResource(R.drawable.review_view_right);
			} else {
				view.setBackgroundResource(R.drawable.review_view_left);
			}
		}

	}

	public void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		// Log.d("listAdapter.getCount() ->", String.valueOf(listAdapter.getCount()));
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
			//Log.d("listItem.getMeasuredHeight() ->", String.valueOf(listItem.getMeasuredHeight()) + " ,totalHeight" + String.valueOf(totalHeight));
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		View titleView = findViewById(R.id.newparty_location_loclayout1);
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)) + titleView.getMeasuredHeight();
		((MarginLayoutParams) params).setMargins(10, 10, 0, 10);
		listView.setLayoutParams(params);
	}

	public OnClickListener clickListeners = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.newparty_location_locphone:

				if (storePhoneBtn.getText().toString() != "") {
					Intent intent = new Intent(Intent.ACTION_CALL);
					intent.setData(Uri.parse("tel:" + storePhoneBtn.getText().toString().trim()));
					startActivity(intent);
				}
				break;
			case R.id.newparty_location_likebtn:
				initLikePlus();
				break;
			case R.id.newparty_location_buildparty:
				Intent intent = new Intent(PartyStoreDetailActivity.this, CreateNewPartyViewActivity.class);
				intent.putExtra("meet_mg_id", mStore.getMg_id());
				intent.putExtra("meet_mg_name", mStore.getMg_name());
				intent.putExtra("meet_mg_address", mStore.getMg_address());
				intent.putExtra("parentIntent", "PartyStoreDetailActivity");
				intent.putExtra("meet_mg_phone", mStore.getMg_phone());
				startActivity(intent);
				break;
			case R.id.newparty_location_comment:
				showMoreLinesInputField();
				break;
			case R.id.newparty_location_locate_button:
				Intent locIntent = new Intent(PartyStoreDetailActivity.this, MapMainActivity.class);
				locIntent.putExtra("storeName", mStore.getMg_name());
				locIntent.putExtra("storeAddr", mStore.getMg_address());
				locIntent.putExtra("long", mStore.getMg_long());
				locIntent.putExtra("lati", mStore.getMg_lati());
				startActivity(locIntent);
			default:
				break;
			}
		}
	};

	public void initCommentsInfos() {
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_MGID, mStore.getMg_id());
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETPARTYSTORECOMMENTS, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_MESSAGE_ALLREVIEWS);
					String[] ss = JSONUtil.JSONStringArrayToStringArray(jsonArray);
					for (int i = 0; i < ss.length; i++) {
						Log.d("commentItem", ss[i]);
					}
					initCommentsFromJSONObject(jsonArray);
				}

			}
		} catch (Exception e) {
			// TODO: handle exception

		}
	}

	public void initComment(String comContent) {
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put("mg_id", mStore.getMg_id());
			jsonData.put("mc_id", mStore.getMg_mc_id());
			jsonData.put(Constant.PARAM_USERID_ONE, UserInfoDAO.getUserInfo(PartyStoreDetailActivity.this).getUserId());
			jsonData.put("issue", 2);
			jsonData.put("state", mStore.getMg_state());
			jsonData.put("parent_id", 0);
			jsonData.put("ring_id", 0);
			jsonData.put("spreadLevel", 0);
			jsonData.put(Constant.PARAM_COMMENT_CONTENT, comContent);
			Log.d("PartyStoreDetailjson", jsonData.toString());
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_STORECOMMENT, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if (status == 1) {
					ViewsUtil.showErrorTip(PartyStoreDetailActivity.this, R.string.party_comment_success);
				}

			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public void initLikePlus() {
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put("mg_id", mStore.getMg_id());
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_STORELIKE, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				Log.d("status>likeplus>", status + "");
				if (status == 1) {
					ViewsUtil.showErrorTip(PartyStoreDetailActivity.this, R.string.party_store_likeplus_success);
				}

			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	private void initCommentsFromJSONObject(JSONArray jsonArray) throws JsonSyntaxException, JSONException {
		Gson gson = new Gson();
		for (int i = 0; i < jsonArray.length(); i++) {
			MsgEntity entity = gson.fromJson(jsonArray.getJSONObject(i).toString(), MsgEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			String key = entity.getMsg_user_nickname() + "-" + entity.getMsg_date();
			item.put("comUser", entity.getMsg_user_nickname());
			String partyDate = entity.getMsg_date();
			String[] strs = partyDate.split(" ");
			String datestr = String.format(getString(R.string.dateformate), strs[2],strs[1],strs[0],strs[3]);
			item.put("comTime",datestr);
			item.put("comContent", entity.getMsg_content());

			mCommentsItems.add(item);
			commentinfos.put(key, entity.getMsg_user_id());
		}

	}

}
